<?php
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class ScorecardModelCourse extends JModel {

	var $_id = null;
	var $_course = null;

	function __construct() {
		parent::__construct();
		$this->_id = JRequest::getVar('courseid', 0, '', 'int');
	}

	function getCourse() {
		if (!$this->_course) {
			$query = " SELECT C.*, C.id as courseid, S.id as scorecardid, S.acr as acr, S.awcr as awcr FROM #__golfcourses C, #__scorecards S" .
					 " WHERE C.scorecardid = S.id" .
					 " AND C.id = '" . $this->_id . "'";
			$this->_db->setQuery($query);
			$course = $this->_db->loadAssoc();
			if ($course) {
				$query = "SELECT * FROM #__scorecard_holes WHERE scorecardid = '" . $course['scorecardid'] . "'";
				$this->_db->setQuery($query);
				$holes = $this->_db->loadAssocList();
				$this->_course = $course;

				if ($holes) {
					foreach ($holes as $hole) {
						$this->_course['holes'][$hole['number']] = $hole;
					}
				}
			}
		}
		return $this->_course;
	}

	function saveCourse() {
		$course =& JTable::getInstance('golfcourse', 'Table');
		$scorecardhole =& JTable::getInstance('scorecardhole', 'Table');
		$scorecard =& JTable::getInstance('scorecard', 'Table');
		$post = JRequest::get('post');

		// Create the course scorecard
		if (!$scorecard->bind($post)) {
			return false;
		}
		if ($post['scorecardid']) {
			$scorecard->id = $post['scorecardid'];
		}
		if (!$scorecard->store()) {
			return false;
		}

		// Then create the course
		$post['scorecardid'] = $scorecard->id;

		if (!$course->bind($post)) {
			return false;
		}
		if ($post['courseid']) {
			$course->id = $post['courseid'];
		}
		if(!$course->store()) {
			return false;
		}

		// Finally, update the scorecard with holes information
		$holes = $post['holes'];
		if ($holes) {
			foreach ($holes as $num => $hole) {
				$hole['number'] = $num;
				$hole['scorecardid'] = $scorecard->id;
				$scorecardhole =& JTable::getInstance('scorecardhole', 'Table');
				if (!$scorecardhole->bind($hole) || !$scorecardhole->store()) {
					continue;
				}
			}
		}
		return true;
	}
}
?>
